# -*- ecoding: utf-8 -*-
# @ModuleName: flask_
# @Author: Kandy
# @Time: 2024-05-17 18:35
# -*- ecoding: utf-8 -*-
# @ModuleName: test2
# @Author: Kandy
# @Time: 2024-05-16 20:10
import json
import time
from multiprocessing import Queue, Process
import threading
from flask import Flask, Response, request
import subprocess
import sys
from nvjpeg import NvJpeg
import util
from SpinLock import SpinLock_mutex
# from nvjpeg

from flask import Flask
import time
from flask_cors import CORS

app = Flask(__name__)
# global list
class Appfront:
    def __init__(self,dict_):
        self.app = Flask(__name__)
        self.dict_ = dict_
        self.setup_routes()
        self.nj = NvJpeg()
        CORS(self.app)
        self.program = {}
        self.send_data = None
        self.personTrack = False
        self.src_list = []
        self.exe_camera_list = []
        self.imagesize = 1280
        self.encoder = ""
        self.m_splock = SpinLock_mutex()

    def run(self):
        self.app.run(host='0.0.0.0', port=5000)
    """
        struct
        {key:[{key:queue}]}
    """
    def gen1(self,camera_id):
        port,index = get_port_id(int(camera_id))
        print(port,index)

        while True:
            # encoder = self.nj.encode(frame)
            # self.m_splock.acquire()
            # if(self.dict_[str(port)].list2[int(index)].qsize() != 0):
            #     encoder = self.dict_[str(port)].list2[int(index)].get()
            #     self.encoder = encoder
            # self.m_splock.acquire()
            encoder = self.dict_[str(port)].list2[int(index)].get()
            self.encoder = encoder

            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + encoder + b'\r\n\r\n')
    def setup_routes(self):
        @self.app.route('/get_stream', methods=['GET', 'POST'])  # 这个地址返回视频流响应
        def test_redis():
            # gas: video:1: name
            # alarm_type = request.args.get("type")
            # print("视频流参数：", alarm_type)
            # camera_id = alarm_type.split("gas:video:")[1].split(":")[0]
            # # print("=========",self.hoisting.camera_list)
            # suoyi=self.hoisting.camera_list.index(int(ca mera_id))
            # self.hoisting.tuiliu[suoyi]=True
            camera_id = request.args.get("cid")
            return Response(self.gen1(camera_id), mimetype='multipart/x-mixed-replace; boundary=frame')

def get_port_id(camera_id):
    '''
    根据传入的摄像头id获取相应的端口号及其对应的索引
    '''
    port = None
    camera_index = None
    port_list = ['5001', '5002', '5003', '5004', '5005', '5031', '5032', '5033', '5034', '5035']

    for i in range(len(port_list)):
        camera_jsonList = util.get_camera_list(int(port_list[i]))  # 端口对应的摄像头信息
        for m in range(len(camera_jsonList)):
            if camera_id == camera_jsonList[m]['camera_id']:
                port = port_list[i]
                camera_index = m
            else:
                continue

    return port, camera_index


def start(dict_):
    front = Appfront(dict_)
    front.run()

if __name__ == '__main__':
    pass
# if __name__ == '__main__':
#     list_ = sys.argv[1]
#     Appfront(list_).run()